import '../NurseReviseInfo/NurseReviseInfo.css';
import axios from 'axios';
import { Input, Select, Button, message, Space } from 'antd';
import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';

function ReviseInformation() {
    const [data, setData] = useState(null);
    const [, setPhotoUrl] = useState('');
    const fileInputRef = useRef(null);
    const [messageApi, contextHolder] = message.useMessage();
    const [isLoading, setIsLoading] = useState(true);
    const [newPassword, setNewPassword] = useState('');
    const [oldPassword, setOldPassword] = useState('');
    const [department, setDepartment] = useState('');
    const [photo, setPhoto] = useState(null);
    const [departmentList, setDepartmentList] = useState([]);
    const navigate = useNavigate();

    useEffect(() => {
        const fetchData = async () => {
            setIsLoading(true);
            try {
                const storedId = localStorage.getItem('dr_id');
                if (!storedId) {
                    throw new Error('No stored ID found');
                }

                const res = await axios.get(`http://8.148.7.123:8000/users/getbyid?id=${storedId}`);
                const userData = res.data.data[0];
                setData(userData);
                setDepartment(userData.department || '');
                setPhotoUrl(userData.head);
                setPhoto(userData.head ? userData.head.split('/').pop() : null);

                const deptRes = await axios.get('http://8.148.7.123:8000/department/departnames');
                setDepartmentList(deptRes.data.data);
            } catch (error) {
                console.error('Error fetching data:', error);
                messageApi.error('Failed to load data');
            } finally {
                setIsLoading(false);
            }
        };

        fetchData();
    }, [messageApi]);

    const handleChange = (value) => {
        setDepartment(value);
    };

    const handlePhotoUpload = (event) => {
        const file = event.target.files?.[0];
        if (file) {
            const url = URL.createObjectURL(file);
            setPhotoUrl(url);
            setPhoto(file.name);
        }
    };

    const handleSubmit = async () => {
        try {
            const res = await axios.post('http://8.148.7.123:8000/doctor/edit_nurse', {
                id: data.id,
                name: data.name,
                idcard: data.idcard,
                phone: data.phone,
                department: department,
                oldpwd: oldPassword || data.password,
                newpwd: newPassword || data.password,
                head: photo,
            });

            if (res.data.code === 1) {
                if (newPassword) {
                    messageApi.success('修改成功，即将跳转到登录页', 2, () => {
                        localStorage.clear();
                        navigate('/login');
                    });
                } else {
                    messageApi.success('修改成功');
                    localStorage.setItem('userData', JSON.stringify({...data, department, head: photo}));
                }
            } else {
                messageApi.error('修改失败，请确认密码是否正确');
            }
        } catch (error) {
            console.error(error);
            messageApi.error('修改失败');
        }
    };

    if (isLoading) {
        return <div>Loading...</div>;
    }

    return (
        <div className="ReviseInformationBox">
            {contextHolder}
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">医生账号</div>
                <Input value={data.account} disabled className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">账号权限</div>
                <Select
                    value={data.purview}
                    style={{ width: 120 }}
                    disabled
                    options={[{ value: data.purview, label: data.purview }]}
                />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">旧密码</div>
                <Input placeholder="************(不修改密码则不用填写)" value={oldPassword} onChange={(e) => setOldPassword(e.target.value)} className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">新密码</div>
                <Input placeholder="*****(不修改密码则不用填写)" value={newPassword} onChange={(e) => setNewPassword(e.target.value)} className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">姓名</div>
                <Input value={data.name} onChange={(e) => setData({ ...data, name: e.target.value })} className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">身份证号</div>
                <Input value={data.idcard} onChange={(e) => setData({ ...data, idcard: e.target.value })} className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">手机号</div>
                <Input value={data.phone} onChange={(e) => setData({ ...data, phone: e.target.value })} className="ReviseInformationItemInputAccount" />
            </div>
            <div className="ReviseInformationItem">
                <div className="ReviseInformationItemTitle">科室更改</div>
                <Select
                    value={department}
                    style={{ width: 120 }}
                    onChange={handleChange}
                    options={departmentList.map((item) => ({ value: item.name, label: item.name }))}
                />
            </div>
            <div className="ReviseInformationItemPhoto">
                <label className="ReviseInformationItemPhotoTitle">更改照片</label>
                <div className="space-y-4">
                    <img
                        src={`http://8.148.7.123:8000/images/headers/${photo}`}
                        alt="图片加载失败"
                        className="phontoImg"
                        onClick={() => fileInputRef.current?.click()}
                    />
                    <input
                        type="file"
                        ref={fileInputRef}
                        className="hidden"
                        accept="image/*"
                        onChange={handlePhotoUpload}
                    />
                    <div className="text-sm text-muted-foreground">点击图片上传新照片</div>
                </div>
            </div>
            <div className="ReviseInformationButtonBox">
                <Space>
                    <Button type="primary" className="ReviseInformationButton" onClick={handleSubmit}>
                        确认修改
                    </Button>
                    <Button className="ReviseInformationButton" onClick={() => window.history.back()}>返回上一级</Button>
                </Space>
            </div>
        </div>
    );
}

export default ReviseInformation;

